package com.hengpeng.itfints.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hengpeng.itfints.config.Configuration;
import com.hengpeng.itfints.config.PageConfigConstants;
import com.hengpeng.itfints.controller.BaseController;

/**
 * <pre>
 * 前台拦截器
 * </pre>
 * @author chenjian
 * @version 1.0, 2011-1-4
 */
public class MemberSessionFilter implements Filter
{

	@Override
	public void destroy()
	{
	}

	private FilterConfig config;

	private String loginPattern;
	
	private String memberCenter;
	
	@Override
	@SuppressWarnings("all")
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException
	{
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String requestUri = request.getRequestURI();
		HttpSession session = request.getSession();
		if (BaseController.getSessionMember(request) != null || (requestUri.indexOf(loginPattern) == -1 && requestUri.indexOf(memberCenter) == -1))
		{
			filterChain.doFilter(servletRequest, servletResponse);
		}
		else
		{
			/* ajax拦截 */
			if (request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest"))
			{
				response.addHeader("sessionstatus", "timeout");

				response.getWriter().flush();
				response.getWriter().close();
			}
			else
			{
				String requestUrl = request.getRequestURL().toString();
				if (request.getQueryString() != null && !request.getQueryString().trim().equals(""))
				{
					requestUrl = requestUrl + "?" + request.getQueryString();
				}
				String encode = java.net.URLEncoder.encode(requestUrl, "utf-8");
				response.sendRedirect(request.getContextPath() + Configuration.getValue(PageConfigConstants.LOGIN_URL)
						+ "?url=" + encode);
			}
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException
	{
		this.config = filterConfig;
		this.loginPattern = config.getServletContext().getInitParameter("loginPattern");
		this.memberCenter = config.getServletContext().getInitParameter("memberCenter");
	}
}
